﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System
{
    /// <summary>
    /// 以内存方式实现事件总线
    /// </summary>
    public class InMemoryEventBus<TEventType> : IEventBus<TEventType>
    {
        private readonly ConcurrentDictionary<TEventType, List<Delegate>> _eventHandlers = new ConcurrentDictionary<TEventType, List<Delegate>>();

        /// <inheritdoc/>
        public void Publish<TEventData>(EventMessage<TEventType, TEventData> eventMessage)
        {
            if (_eventHandlers.TryGetValue(eventMessage.EventType, out var handlers))
            {
                foreach (var handler in handlers)
                {
                    if (handler is Func<EventMessage<TEventType, TEventData>, Task> func)
                    {
                        //((Func<EventMessage<TEventType, TEventData>, Task>)handler)(eventMessage);
                        func(eventMessage);
                    }
                    else if (handler is Action<EventMessage<TEventType, TEventData>> action)
                    {
                        action(eventMessage);
                    }
                }
            }
        }

        /// <inheritdoc/>
        public void Subscribe<TEventData>(TEventType eventType, Func<EventMessage<TEventType, TEventData>, Task> handler)
        {
            if (!_eventHandlers.ContainsKey(eventType))
            {
                _eventHandlers[eventType] = new List<Delegate>();
            }
            _eventHandlers[eventType].Add(handler);
        }

        /// <inheritdoc/>
        public void Subscribe<TEventData>(TEventType eventType, Action<EventMessage<TEventType, TEventData>> handler)
        {
            if (!_eventHandlers.ContainsKey(eventType))
            {
                _eventHandlers[eventType] = new List<Delegate>();
            }
            _eventHandlers[eventType].Add(handler);
        }
    }
}
